package com.alienlab.finder.web.rest;
import com.alienlab.finder.domain.Relationship;
import com.alienlab.finder.service.RelationshipService;
import com.alienlab.finder.service.dto.RelationshipDTO;
import com.alienlab.finder.service.dto.UserState;
import com.alienlab.finder.web.rest.errors.BadRequestAlertException;
import com.alienlab.finder.web.rest.util.ErrorResult;
import com.alienlab.finder.web.rest.util.HeaderUtil;
import com.alienlab.finder.web.rest.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Relationship.
 */
@RestController
@RequestMapping("/api")
public class RelationshipResource {

    private final Logger log = LoggerFactory.getLogger(RelationshipResource.class);

    private static final String ENTITY_NAME = "relationship";

    private final RelationshipService relationshipService;

    public RelationshipResource(RelationshipService relationshipService) {
        this.relationshipService = relationshipService;
    }

    /**
     * POST  /relationships : Create a new relationship.
     *
     * @param main_open_id,second_open_id,relation the relationship to create
     * @return the ResponseEntity with status 201 (Created) and with body the new relationship, or with status 400 (Bad Request) if the relationship has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @ApiOperation(value="创建用户间关系")
    @PostMapping("/relationships")
    public ResponseEntity createRelationship( @RequestParam String main_open_id,@RequestParam String second_open_id) throws Exception {
        log.debug("REST request to creat Relationship");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        if ("".equals(second_open_id)|| second_open_id == null) {
            throw new BadRequestAlertException("未获取到second_open_id", ENTITY_NAME, "second_open_id do not exist");
        }
        Relationship result = relationshipService.creatRelation(main_open_id, second_open_id);
        if (result!=null){
            return  ResponseEntity.ok(result);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());

        }
    }

    /**
     * PUT  /relationships : Updates an existing relationship.
     *
     * @return the ResponseEntity with status 200 (OK) and with body the updated relationship,
     * or with status 400 (Bad Request) if the relationship is not valid,
     * or with status 500 (Internal Server Error) if the relationship couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @ApiOperation(value="更新用户间关系")
    @PutMapping("/relationships")
    public ResponseEntity updateRelationship(@RequestParam String main_open_id,@RequestParam String second_open_id,@RequestParam String relation,@RequestParam String distance,@RequestParam String nickname) throws Exception {
        log.debug("REST request to update Relationship ");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        if ("".equals(second_open_id)|| second_open_id == null) {
            throw new BadRequestAlertException("未获取到second_open_id", ENTITY_NAME, "second_open_id do not exist");
        }
        Relationship result = relationshipService.updateRelation(main_open_id, second_open_id, relation, distance, nickname);
        if (result!=null){
            return  ResponseEntity.ok(result);
        }else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }

    @ApiOperation(value="获取用户的朋友列表")
    @GetMapping("/relationships")
    public ResponseEntity  getRelationshipsList(@RequestParam String main_open_id) {

        log.debug("REST request to 获取用户的朋友列表");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        List<RelationshipDTO> relationshipList = relationshipService.findRelationsByMainopenid(main_open_id);
        return ResponseEntity.ok(relationshipList);
    }


    @ApiOperation(value="获取用户间关系")
    @GetMapping("/relationships/get")
    public ResponseEntity  getRelationship(@RequestParam String main_open_id,@RequestParam String second_open_id) {

        log.debug("REST request to 获取用户间关系");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        if ("".equals(second_open_id)|| second_open_id == null) {
            throw new BadRequestAlertException("未获取到second_open_id", ENTITY_NAME, "second_open_id do not exist");
        }
        Relationship relationship = relationshipService.getRelation(main_open_id, second_open_id);
        return ResponseEntity.ok(relationship);
    }

    @ApiOperation(value="获取被监控人在线状态")
    @GetMapping("/relationships/state")
    public ResponseEntity  getState(@RequestParam String main_open_id) {

        log.debug("REST request to 获取被监控人在线状态");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        List<UserState> relationshipList = relationshipService.getOnlineState(main_open_id);
        return ResponseEntity.ok(relationshipList);
    }

    @ApiOperation(value="被监控人更新在线状态")
    @PutMapping("/relationships/sendstate")
    public ResponseEntity  sendStatetoMaster(@RequestParam String second_open_id) {

        log.debug("REST request to 被监控人更新在线状态");
        if ("".equals(second_open_id)|| second_open_id == null) {
            throw new BadRequestAlertException("未获取到second_open_id", ENTITY_NAME, "second_open_id do not exist");
        }
        try {
            relationshipService.sendOnlineStateRequset(second_open_id);
            return ResponseEntity.ok("{\"flag\":true}");
        } catch (Exception e) {
            e.printStackTrace();
            return  ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }


    /**
     * GET  /relationships : get all the relationships.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of relationships in body
     */
    @GetMapping("/relationships/pages")
    public ResponseEntity<List<Relationship>> getAllRelationships(Pageable pageable) {
        log.debug("REST request to get a page of Relationships");
        Page<Relationship> page = relationshipService.findAll(pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/relationships");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /relationships/:id : get the "id" relationship.
     *
     * @param id the id of the relationship to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the relationship, or with status 404 (Not Found)
     */
    @GetMapping("/relationships/{id}")
    public ResponseEntity<Relationship> getRelationship(@PathVariable Long id) {
        log.debug("REST request to get Relationship : {}", id);
        Optional<Relationship> relationship = relationshipService.findOne(id);
        return ResponseUtil.wrapOrNotFound(relationship);
    }


    @ApiOperation(value="解除用户间关系")
    @DeleteMapping("/relationships")
    public ResponseEntity deleteRelationship(@RequestParam String main_open_id,@RequestParam String second_open_id)  {
        log.debug("REST request to delete Relationship ");
        if ("".equals(main_open_id)|| main_open_id == null) {
            throw new BadRequestAlertException("未获取到main_open_id", ENTITY_NAME, "main_open_id do not exist");
        }
        if ("".equals(second_open_id)|| second_open_id == null) {
            throw new BadRequestAlertException("未获取到second_open_id", ENTITY_NAME, "second_open_id do not exist");
        }
        try {
            relationshipService.deleteRelation(main_open_id, second_open_id);
            return ResponseEntity.ok("{\"flag\":true}");
        } catch (Exception e) {
            e.printStackTrace();
            return  ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ErrorResult());
        }

    }





}
